package com.hbu.fleastreet.controller.backend;

import com.hbu.fleastreet.common.Constant;
import com.hbu.fleastreet.entity.Order;
import com.hbu.fleastreet.entity.OrderItem;
import com.hbu.fleastreet.entity.Result;
import com.hbu.fleastreet.entity.ResultCode;
import com.hbu.fleastreet.exception.OrderException;
import com.hbu.fleastreet.services.IOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.IOException;
import java.util.List;

/**
 * 管理后端针对订单处理等
 */
@Controller
@RequestMapping("/manager/order")
public class ManagerOrderController {
	@Autowired
	private IOrderService orderService;

	/**
	 * 打开订单列表页面
	 * @return
	 */
	@RequestMapping("/list")
	public String toList() {
		return "backend/order/list";
	}

	/**
	 * 分页查询
	 * @param pageindex
	 * @param pageSize
	 * @return
	 */
	@ResponseBody
	@PostMapping("/list/{pageindex}")
	public Result<List<Order>> listProduct(@PathVariable("pageindex") Integer pageindex,
			@RequestParam(defaultValue = "7", value = "pageSize", required = false) Integer pageSize) {
		List<Order> list = null;
		try {
			list = orderService.findOrderByIndex(pageindex, pageSize).getList();
		} catch (OrderException e) {
			return new Result<List<Order>>(ResultCode.ERROR, e.getMessage());
		}
		return new Result<List<Order>>(ResultCode.SUCCESS, list);
	}

	/**
	 * 用于获取分页时总数
	 * @return
	 */
	@ResponseBody
	@GetMapping("/total")
	public Result<Integer> getTotal() {
		int total = orderService.countAll();
		return new Result<>(ResultCode.SUCCESS, total);
	}

	/**
	 * 获取订单项
	 * @param orderId
	 * @return
	 **/

	@ResponseBody
	@GetMapping("/item/detail/{orderId}")
	public Result<List<OrderItem>> getDetail(@PathVariable("orderId") int orderId) {
		List<OrderItem> list = orderService.getItemByOrderId(orderId);
		return new Result<List<OrderItem>>(ResultCode.SUCCESS, list);
	}

	/**
	 * 状态修改
	 * @return
	 * **/

	@ResponseBody
	@PostMapping(value = "/state/{orderId}")
	public Result<Boolean> send(@PathVariable("orderId") Integer orderId) throws IOException {
		try {
			orderService.updateOrderStateAndOrderItemState(orderId, Constant.ORDER_STATE_3);
		} catch (OrderException e) {
			return new Result<Boolean>(ResultCode.ERROR, e.getMessage());
		}
		return new Result<Boolean>(ResultCode.SUCCESS, true);
	}

}
